import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { clearUserInfo, clearToken } from "../store/modules/userInfo";
import { message } from 'antd';
import store from "../store";

export interface Result<T> {
  code: number;
  msg: string;
  data: T;
};

// 环境配置
const baseURL: string = process.env.REACT_APP_API_URL as string;
// 请求白名单不需要token验证的
const whitelist: string[] = [];


// 导出Request类，可以用来自定义传递配置来创建实例
export class Request {
  // axios 实例
  instance: AxiosInstance;
  // 基础配置，url和超时时间
  baseConfig: AxiosRequestConfig = { baseURL, timeout: 50000 };

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(Object.assign({}, this.baseConfig, config));

    this.instance.interceptors.request.use(
      (config: any) => {
        const { userInfo } = store.getState()
        if (!whitelist.includes(config.url as string)) {
          if (userInfo.token) {
            config.headers!.Authorization = userInfo.token;
          }
        }
        return config;
      },
      (err: any) => {
        return Promise.reject(err);
      }
    );

    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        if (res.data.code === 999998) {
          store.dispatch(clearToken());
          store.dispatch(clearUserInfo());
          window.location.hash = "/login";
        }
        return res.data;
      },
      (err: any) => {

        switch (err.response.status) {
          case 400:
            message.error("请求错误(400)");
            break;
          case 401:
            message.error("未授权，请重新登录(401)");
            window.location.hash = "/login";
            break;
          case 403:
            message.error("拒绝访问(403)");
            break;
          case 404:
            message.error("请求出错(404)");
            break;
          case 408:
            message.error("请求超时(408)");
            break;
          case 500:
            message.error("服务器错误(500)");
            break;
          case 501:
            message.error("服务未实现(501)");
            break;
          case 502:
            message.error("网络错误(502)");
            break;
          case 503:
            message.error("服务不可用(503)");
            break;
          case 504:
            message.error("网络超时(504)");
            break;
          case 505:
            message.error("HTTP版本不受支持(505)");
            break;
          default:
            message.error(`连接出错(${err.response.status})!`);
        }
        return Promise.reject(err.response);
      }
    );
  }

  // 定义请求方法
  public request<T = any>(config: AxiosRequestConfig): Promise<Result<T>> {
    return this.instance.request(config);
  }
}

// 默认导出Request实例
export default new Request({})